package com.peng.utils;


import com.dc.encrypt4.Base64Utils;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class EncryptUtils {
    private static final String ALGORITHM_CBC = "AES/CBC/PKCS5Padding"; // "算法/模式/补码方式"
    private static final String AES = "AES";
    public static final String AES_KEY = "0123456789000000";//秘钥，必须为16个字符组成
    public static final String IV = "0123456789123123"; // 偏移量，必须为16个字符组成
    private static final String CHARSET = "UTF-8";



    /**
     * @description:  AES算法CBC模式加密
     * @Param: text
     * @Return java.lang.String
     * @author pengyf
     */ 
    public static String aesEncrypt(String aeskeyStr, String ivStr, String text) throws Exception {
        byte[] raw = aeskeyStr.getBytes();
        SecretKeySpec skeySpec = new SecretKeySpec(raw, AES);
        Cipher cipher = Cipher.getInstance(ALGORITHM_CBC);
        IvParameterSpec iv = new IvParameterSpec(ivStr.getBytes());//使用CBC模式，需要一个向量iv，可增加加密算法的强度
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
        byte[] encrypted = cipher.doFinal(text.getBytes(CHARSET));
        return Base64Utils.encode(encrypted);//此处使用BASE64做转码功能，同时能起到2次加密的作用。
    }

    /**
     * @description:  AES算法CBC模式解密
     * @Param: encryptText
     * @Return java.lang.String
     * @author pengyf
     */
    public static String aesDecrypt(String aeskeyStr, String ivStr, String encryptText) throws Exception {
        byte[] raw = aeskeyStr.getBytes(CHARSET);
        SecretKeySpec skeySpec = new SecretKeySpec(raw, AES);
        Cipher cipher = Cipher.getInstance(ALGORITHM_CBC);
        IvParameterSpec iv = new IvParameterSpec(ivStr.getBytes());
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
        byte[] original = cipher.doFinal(Base64Utils.decode(encryptText));//先用base64解密
        String originalString = new String(original,CHARSET);
        return originalString;
    }

}